package cn.mrlong.base.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.net.http.SslError;
import android.os.Build;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * 作者：BINGO
 * 时间：2021/04/23 09:46
 */
public class WebViewUtils {
    private WebView webview;
    private String goToUrl;
    private StatuListener listener;
    public JsCallBack jsCallBack;

    public WebViewUtils(WebView webview) {
        this.webview = webview;
    }

    public WebViewUtils setUrl(String url) {
        goToUrl = url;
        return this;
    }

    public WebViewUtils setStatuListener(StatuListener statulistener) {
        listener = statulistener;
        return this;
    }


    public WebViewUtils(WebView webview, String goToUrl) {
        this.webview = webview;
        this.goToUrl = goToUrl;
    }

    /**
     * 自定义 UserAgent
     *
     * @param userAgentString UserAgent字符串
     * @return
     */
    public WebViewUtils setUserAgentString(String userAgentString) {
        webview.getSettings().setUserAgentString(webview.getSettings().getUserAgentString() + userAgentString);
        Log.e("=============>", webview.getSettings().getUserAgentString());
        return this;
    }

    /**
     * 打开WebViewLocalStorage
     *
     * @param appCachePath 存储缓存位置
     */
    public WebViewUtils openLocalStorage(String appCachePath) {
        //使用缓存，否则localstorage等无法使用
        //webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        //String appCachePath = context.getCacheDir().getAbsolutePath();
        webview.getSettings().setAppCachePath(appCachePath);
        webview.getSettings().setAllowFileAccess(true);
        //webview.getSettings().setAppCacheEnabled(true);
        Log.e("=============>", "存储缓存位置" + appCachePath);
        return this;
    }

    /**
     * 开始加载
     */
    @SuppressLint("SetJavaScriptEnabled")
    public void startWevView() {
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.getSettings().setDatabaseEnabled(true);
        webview.getSettings().setAppCacheEnabled(true);
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setSavePassword(true);
        webview.getSettings().setSupportZoom(true);
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setBuiltInZoomControls(true);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setUseWideViewPort(true);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (null != listener)
                    listener.onPageFinished();
            }

            //处理网页加载失败时
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                if (null != listener)
                    listener.error(error);

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (null != listener) {
                    listener.onProgressChanged(newProgress);
                    Log.e("=============>", newProgress + "");
                }
            }

            public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                Log.d("WebView===>", message + " -- From line "
                        + lineNumber + " of "
                        + sourceID);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d("WebView===>", "[" + consoleMessage.messageLevel() + "] " + consoleMessage.message() + "(" + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + ")");
                return super.onConsoleMessage(consoleMessage);
            }


        });
        webview.loadUrl(goToUrl);
    }

    /**
     * 与activity 的 back按钮绑定
     *
     * @param activity
     */
    public void goBack(Activity activity) {
        if (null != webview && webview.canGoBack()) {
            //获取历史列表
            WebBackForwardList mWebBackForwardList = webview
                    .copyBackForwardList();
            //判断当前历史列表是否最顶端,其实canGoBack已经判断过
            if (mWebBackForwardList.getCurrentIndex() > 0) {
                //获取历史列表
                String historyUrl = mWebBackForwardList.getItemAtIndex(
                        mWebBackForwardList.getCurrentIndex() - 1).getUrl();
                Log.e("======>",historyUrl);
                //按照自己规则检查是否为可跳转地址
                //注意:这里可以根据自己逻辑循环判断,拿到可以跳转的那一个然后webView.goBackOrForward(steps)
                if (historyUrl.contains(webview.getUrl())) {
                    //执行跳转逻辑
                    activity.finish();
                } else {
                    webview.goBack();
                }
            }
        } else {
            activity.finish();
        }
    }

    /**
     * 销毁
     */
    public void webViewRelease() {
        if (webview != null) {
            webview.clearCache(true);
            webview.clearFormData();
            webview.clearMatches();
            webview.clearSslPreferences();
            webview.clearDisappearingChildren();
            webview.clearHistory();
            webview.clearAnimation();
            webview.loadUrl("about:blank");
            webview.removeAllViews();
            webview.freeMemory();
        }
    }

    /**
     * 与activity OnResume 中调用
     */
    public void webViewOnResume() {
        if (null != webview) webview.onResume();
    }

    /**
     * 与activity OnPause 中调用
     */
    public void webViewOnPause() {
        if (null != webview) webview.onPause();
    }

    /**
     * js 调用 java 实体类
     */
    class JsKit {
        /**
         * js 调用 java 方法
         *
         * @param json
         */
        @JavascriptInterface
        public void callJava(String json) {
            //执行回调java
            if (null != jsCallBack) jsCallBack.callBack(json);
            Log.e("=============>", "" + json);
        }
    }


    /**
     * 开启js to java 并回调
     *
     * @param jsCallBack
     * @return
     */
    public WebViewUtils openJsToJava(JsCallBack jsCallBack) {
        this.jsCallBack = jsCallBack;
        webview.addJavascriptInterface(new JsKit(), "jsToJava");
        return this;
    }

    /**
     * java调用js代码
     *
     * @param methodName 方法名
     * @param paramsJson json参数
     */
    public void callJS(String methodName, String paramsJson) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webview.evaluateJavascript("javascript:" + methodName + "(" + paramsJson + ")", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        } else {
            webview.loadUrl("javascript:" + methodName + "(" + paramsJson + ")");
        }
    }

    /**
     * 加载进度状态
     */
    public interface StatuListener {
        void onProgressChanged(int i);

        void error(WebResourceError e);

        void onPageFinished();
    }

    /**
     * js to java 回调
     */
    interface JsCallBack {
        void callBack(String json);
    }
}
